package com.buddy.summary.code.algorithm;

public class Array {

    private int[] arr;
    private int size;

    private Array(int capacity) {
        arr = new int[capacity];
        size = 0;
    }

    private void insert(int ele,int index){
        if (index < 0 || index > size){
            throw new IndexOutOfBoundsException("超出数组范围");
        }
        if (size >= arr.length){
            resize();
        }
        //从右向左循环,将元素逐个向右挪一位
        for (int i = size-1;i>index;i--){
            arr[i+1] = arr[i];
        }
        arr[index] = ele;
        size++;
    }

    /**
     * 扩容
     */
    private void resize() {
        int[] newArr = new int[arr.length*2];
        System.arraycopy(arr,0,newArr,0,arr.length);
        arr = newArr;
    }

    private void output() {
        for (int i=0;i<size;i++){
            System.out.print(arr[i]);
        }
        System.out.println("");
    }

    private int delete(int index){
        //判断访问下标是否越界
        if (index < 0 || index > size){
            throw new IndexOutOfBoundsException("数组越界");
        }
        int deleteElement = arr[index];
        //从左向右循环,将元素逐个向左挪动1位
        for (int i = index;i<size -1 ;i++){
            arr[i] = arr[i+1];
        }
        size -- ;
        return deleteElement;
    }

    public static void main(String[] args) {
        Array array = new Array(10);
        for (int i=1;i<20;i++){
            array.insert(i,i-1);
            array.output();
        }
        for (int i=10;i>0;i--){
            array.delete(i);
            array.output();
        }
    }

}
